<template>
  <el-dialog :title="showTitle" :visible="showDialog" width="40%" @close="close">
    <el-form
      ref="form"
      :rules="rules"
      label-width="100px"
      label-position="left"
      :model="form"
    >
      <el-form-item label="部门名称" prop="name">
        <el-input
          v-model.trim="form.name"
          placeholder="请输入部门名称"
        />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model.trim="form.code" placeholder="请输入部门编码" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select
          v-model="form.manager"
          @focus="focusFn"
        >
          <el-option
            v-for="item in employeeList"
            :key="item.id"
            :lable="item.username"
            :value="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input
          v-model="form.introduce"
          resize="none"
          placeholder="部门介绍"
          type="textarea"
          :rows="3"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="addFn">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script>
import {
  addDepartment, getDepartementList, getDepartmentDetail, updateDepartment
} from '@/api/departements'
import { getEmployeeSimple } from '@/api/employees'
export default {
  name: 'AddDept',
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    nodeData: {
      type: Object,
      required: true
    }
  },
  data() {
    const checkName = async(rule, value, callback) => {
      // 1.发送请求，获取到最新所有的部门信息
      const { depts } = await getDepartementList()
      let result
      if (this.form.id) {
        // 修改
        // 1.如果部门名称没有发生变化，是允许的
        if (value === this.nodeData.name) return callback()
        // 2. 如果部门名称发生了改变，需要判断value和兄弟部门的名称是否一致
        result = depts.filter(item => item.pid === this.nodeData.pid)
      } else {
        // 2.根据nodeData找到它的所有子部门
        result = depts.filter(item => item.pid === this.nodeData.id)
        // 3.判断value和这些子部门的名称是否是重复的
      }
      // console.log(depts)
      const has = result.some(item => item.name === value)
      has ? callback(new Error(`${value}已经存在了`)) : callback()
    }

    const checkCode = async(rule, value, callback) => {
      if (this.form.id) {
        // 修改功能允许部门编码和以前一致
        if (value === this.nodeData.code) {
          return callback()
        }
      }
      // 添加功能
      // 1.发送请求，获取到最新所有的部门信息
      const { depts } = await getDepartementList()
      // 2.判断value是否和其他部门的code重复了
      const has = depts.some(item => item.code === value)
      has ? callback(new Error(`${value}已经存在了`)) : callback()
    }
    return {
      form: {
        name: '',
        manager: '',
        introduce: '',
        code: ''
      },
      employeeList: [],
      rules: {
        name: [
          { required: true, message: '部门名称不能为空' },
          { max: 50, message: '部门名称长度为1-50' },
          { validator: checkName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空' },
          { max: 50, message: '部门编码长度为1-50' },
          { validator: checkCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '请选择部门负责人' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空' },
          { max: 300, message: '部门介绍长度为1-300' }
        ]
      }
    }
  },
  computed: {
    showTitle() {
      return this.form.id ? '编辑部门' : '新增部门'
    }
  },
  methods: {
    close() {
      this.$emit('close')
      this.$refs.form.resetFields()
      this.form = {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      }
      // console.log(this.nodeData)
    },
    async focusFn() {
      const data = await getEmployeeSimple()
      // console.log(data)
      this.employeeList = data
    },
    addFn() {
      // 1.整体表单校验
      this.$refs.form.validate(async valid => {
        if (!valid) return
        if (this.form.id) {
          await updateDepartment(this.form)
        } else {
          // 调用新增接口 添加父部门ID
          await addDepartment({ ...this.form, pid: this.treeNode.id })
        }
        // 3.让父组件重新渲染
        this.$emit('getDeparts')
        // 1.提示信息
        this.$message.success('修改成功')
        // 2.关闭弹框
        this.$emit('close')
      })
    },
    async getInfo(id) {
      const data = await getDepartmentDetail(id)
      this.form = data
    }
  }
}
</script>

<style>

</style>
